<template>
  <el-dialog v-model="dialogVisible" title="智能助手" width="800">
<!--    <template #header="{ close, titleId, titleClass }">-->
<!--      <div class="my-header">-->
<!--        <el-button type="danger" @click="handleCreate">-->
<!--          新建窗口-->
<!--        </el-button>-->
<!--      </div>-->
<!--    </template>-->
    <div class="kefubox" ref="kefubox">
      <div v-for="message in chatHistory" :key="message.id" class="message"
           :class="{'user-message': message.role === 'user', 'system-message': message.role === 'system'}">
        <div class="avatar">{{ message.role === 'user' ? store.UserInfo.user.username : 'kimi' }}</div>
        <img :src="getAvatarSrc(message.role)" alt="User Avatar"
             style="width: 30px;height: 30px;border-radius:5px;margin: 2px ">
        <div class="message-content">
          <span v-html="message.content"></span>
        </div>

      </div>
      <svg v-if="disabled" viewBox="0 0 150 50" style="height: 1rem">
        <circle cx="20" cy="25" r="8" fill="#2c2dad">
          <animate attributeName="opacity" values="1;0" dur="1s" repeatCount="indefinite"/>
        </circle>
        <circle cx="50" cy="25" r="8" fill="#2c2dad">
          <animate attributeName="opacity" values="1;0" begin="0.2s" dur="1s" repeatCount="indefinite"/>
        </circle>
        <circle cx="80" cy="25" r="8" fill="#2c2dad">
          <animate attributeName="opacity" values="1;0" begin="0.4s" dur="1s" repeatCount="indefinite"/>
        </circle>
        <circle cx="110" cy="25" r="8" fill="#2c2dad">
          <animate attributeName="opacity" values="1;0" begin="0.6s" dur="1s" repeatCount="indefinite"/>
        </circle>
        <circle cx="140" cy="25" r="8" fill="#2c2dad">
          <animate attributeName="opacity" values="1;0" begin="0.8s" dur="1s" repeatCount="indefinite"/>
        </circle>
      </svg>
    </div>
    <!-- 输入框 -->
    <template #footer>
      <div class="iptbox">
        <el-input v-model="userLastInput" placeholder="请输入问题..." @keyup.enter="sendMessage"/>
        <el-button @click="sendMessage" :disabled="disabled">发送</el-button>
      </div>
    </template>
  </el-dialog>
</template>


<script setup>
import {ref, onMounted, onBeforeUnmount, computed, defineEmits, watch,nextTick} from 'vue';
import useFormatMarkdown from '../../hooks/useFormatMarkdown.js'; // 导入你的hook
import {useAlertsStore} from "@/store/modules/home.js";
import userAvatar from '@/assets/kimi.png';
import axios from "axios";
import {ElMessage} from "element-plus";

const store = useAlertsStore()
const userLastInput = ref('');
const chatHistory = ref([]);
const disabled = ref(false)
const emit = defineEmits(['update:visible'])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})
const dialogVisible = computed({
  get() {
    return props.visible
  },
  set(val) {
    emit('update:visible', val)
  }
})

const handleCreate = () => {

}
const getAvatarSrc = (role) => {
  const userAvatarPath = store.UserInfo.user.avatar;
  return role === 'user' ? userAvatarPath : userAvatar;
};
// 加载本地存储中的聊天历史
onMounted(() => {
  const savedHistory = localStorage.getItem('chatHistory');
  if (savedHistory) {
    chatHistory.value = JSON.parse(savedHistory).map(msg => ({
      ...msg,
      content: msg.role === 'system' ? useFormatMarkdown(msg.content) : msg.content
    }));
  }
});

// 页面卸载前保存聊天历史到本地存储
onBeforeUnmount(() => {
  localStorage.setItem('chatHistory', JSON.stringify(chatHistory.value));
});

const sendMessage = async () => {
  const userInput = userLastInput.value.trim();
  if (!userInput) {
    ElMessage.warning('请输入您的问题!!!')
    return
  };
  if (!store.UserInfo.user.id) {
    ElMessage.warning('请先登录在进行使用!!!')
    return
  }
  disabled.value = true


  const userMessage = {
    role: 'user',
    content: userInput,
    id: Date.now().toString(),
  };
  addMessage(userMessage);

  try {
    const response = await axios({
      url: 'http://localhost:3300/ceshi',
      method: 'post',
      data: {
        prompt: chatHistory.value.concat(userMessage),
        en_name:store.UserInfo.user.username,
        user_message:userLastInput.value,
        stream: false
      },
      onDownloadProgress: ({event}) => {
        userLastInput.value = '';
        const xhr = event.target;
        const {responseText} = xhr;
        handleStreamData(responseText);
      }
    });
  } catch (error) {
    const systemReply = {
      role: 'system',
      content: useFormatMarkdown('perminute限流,请稍后重试!!!'), // 使用hook处理Markdown格式的文本
      id: Date.now().toString(),
    }
    addMessage(systemReply);
    console.log('Error during chat process:', error);
  }
};

const handleStreamData = (responseText) => {
  const arr = responseText.split("\n\r").filter(item => item !== "");
  const item = arr[arr.length - 1];
  try {
    const p = JSON.parse(item);
    if (p.code && p.code === 500) {
      const systemReply = {
        role: 'system',
        content: useFormatMarkdown('perdayMinute限流,请稍后重试!!!'), // 使用hook处理Markdown格式的文本
        id: Date.now().toString(),
      }
      addMessage(systemReply);
      disabled.value = false
    }
    const systemReply = {
      role: 'system',
      content: useFormatMarkdown(p.total), // 使用hook处理Markdown格式的文本
      id: Date.now().toString(),
    }
    addMessage(systemReply);
    disabled.value = false
  } catch (error) {
    // 可能是因为JSON不完整导致的解析错误
    console.error('Error parsing stream data:', error);
  }
};

const addMessage = (message) => {
  chatHistory.value.push(message);
  // 每次添加消息后更新本地存储
  localStorage.setItem('chatHistory', JSON.stringify(chatHistory.value));
  scrollToBottom(); // 调用滚动函数
};
watch(dialogVisible, (newValue) => {
  if (newValue) {
    scrollToBottom();
  }
});
const kefubox = ref(null)
const scrollToBottom = () => {
  // 使用 nextTick 确保 DOM 更新完成
  nextTick(() => {
    const container = kefubox.value
    container.scrollTop = container.scrollHeight;
  });
};
</script>


<style scoped>
.kefubox {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.message {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
  justify-content: center;
}

.user-message {
  justify-content: flex-end;
}

.system-message {
  justify-content: flex-start;
}

.avatar {
  margin: 0 10px;
}

.message-content {
  flex: 1;
  max-width: calc(100% - 60px);
  padding: 8px;
  border-radius: 4px;
}

.user-message .message-content {
  background-color: #e6e6e6;
  margin-left: auto;
}

.system-message .message-content {
  background-color: #cce7ff;
  margin-right: auto;
  text-align: left;
}

.iptbox {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.el-input {
  flex: 1;
  margin-right: 5px;
}
</style>